#!/usr/bin/env python3
"""
AI角色扮演应用后端启动脚本
这是应用的唯一启动入口
"""
import uvicorn
import sys
import os
import argparse
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from app.core.config import settings


def print_startup_info():
    """打印启动信息"""
    print("=" * 60)
    print(f"🚀 启动 {settings.APP_NAME} v{settings.APP_VERSION}")
    print("=" * 60)
    print(f"📊 调试模式: {'开启' if settings.DEBUG else '关闭'}")
    print(f"🗄️  数据库: {settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}")
    print(f"🤖 Ollama: {settings.OLLAMA_BASE_URL}")
    print(f"🧠 模型: {settings.OLLAMA_MODEL}")
    print(f"💾 缓存: 内存缓存")
    print(f"🌐 服务地址: http://0.0.0.0:8000")
    print(f"📚 API文档: http://localhost:8000/docs")
    print(f"❤️  健康检查: http://localhost:8000/health")
    print("=" * 60)


def main():
    """主启动函数"""
    parser = argparse.ArgumentParser(description="AI角色扮演应用后端启动器")
    parser.add_argument("--host", default="0.0.0.0", help="绑定主机地址 (默认: 0.0.0.0)")
    parser.add_argument("--port", type=int, default=8000, help="绑定端口 (默认: 8000)")
    parser.add_argument("--reload", action="store_true", help="启用热重载 (默认: 根据DEBUG设置)")
    parser.add_argument("--log-level", choices=["debug", "info", "warning", "error"], 
                       help="日志级别 (默认: 根据DEBUG设置)")
    
    args = parser.parse_args()
    
    # 打印启动信息
    print_startup_info()
    
    # 确定启动参数
    reload = args.reload if args.reload is not None else settings.DEBUG
    log_level = args.log_level if args.log_level else ("debug" if settings.DEBUG else "info")
    
    print(f"🔧 启动参数: host={args.host}, port={args.port}, reload={reload}, log_level={log_level}")
    print("=" * 60)
    
    try:
        # 启动服务器
        uvicorn.run(
            "main:app",
            host=args.host,
            port=args.port,
            reload=reload,
            log_level=log_level,
            access_log=True
        )
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
